package org.jeecg.modules.system.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.modules.mall.entity.TbMnUser;
import org.jeecg.modules.mall.service.ITbMnUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class InterceptControllerAspect {

     @Autowired
     private  RedisUtil redisUtil;

    @Autowired
    private ITbMnUserService tbMnUserService;
    //can  update args token transmit
    @Pointcut("execution(* org.jeecg.modules.appuser.api..*.*(..))")
    public void interceptController() {

    }

    @Around("interceptController()")
    public Object handle(ProceedingJoinPoint joinPoint) throws Throwable {


        HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
        String token = TokenUtils.getTokenByRequest(request);

        if (null == token) {
           // return joinPoint.proceed();
            return Result.error("请登陆!");
        }
        log.info("----app--token valid---------"+token);

        String user_id = JwtUtil.getAppUserId(token);
        log.info("-- ---user_id----" + user_id);
        if (null != user_id) {
            if (null == redisUtil) {
                log.info("---- null---------redisUtil-------------------------------");
            }
            TbMnUser tbMnUser= tbMnUserService.getById(user_id);
            if(null==tbMnUser){
                return Result.error("用户不存在，请注册!");
            }
            log.info("---- -tbMnUser.getPhone()----"+tbMnUser.getPhone());
            String redis_token = (String) redisUtil.get(JwtUtil.getTokenKey(user_id));
            log.info("----redis_token---1---- ----"+redis_token);
            if (null == redis_token || !redis_token.equals(token)) {
                return Result.error("token失效!");
            }
        }

        log.info("app token:" + token);
        try {
            return joinPoint.proceed();
        } finally {
            log.info("app aspect after.-----------------");
        }
    }
}